package BC;

import org.bouncycastle.jce.provider.BouncyCastleProvider;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.Certificate;
import java.util.Enumeration;

public class JksToPfx {
    public static void ToPFX(String pathSrc, String pathDst, char[] passwd) throws IOException, KeyStoreException, CertificateException, NoSuchAlgorithmException, NoSuchProviderException, UnrecoverableKeyException {
        //读PFX证书，用密钥解密证书
        Security.addProvider(new BouncyCastleProvider());
        FileInputStream fs = new FileInputStream(pathSrc);
        KeyStore store = KeyStore.getInstance("JKS");
        store.load(fs,passwd);
        fs.close();

        KeyStore outputKeyStore = KeyStore.getInstance("PKCS12","BC");
        outputKeyStore.load(null, passwd);
        Enumeration enums = store.aliases();
        while (enums.hasMoreElements()) {
            String keyAlias = (String) enums.nextElement();
            System.out.println("alias=[" + keyAlias + "]");
            if (store.isKeyEntry(keyAlias)) {
                Key key = store.getKey(keyAlias, passwd);
                Certificate[] certChain = store.getCertificateChain(keyAlias);
                outputKeyStore.setKeyEntry(keyAlias, key, passwd, certChain);
            }
        }
        FileOutputStream out = new FileOutputStream(pathDst);
        outputKeyStore.store(out, passwd);
        out.close();
    }
    public static void main(String[] args) throws CertificateException, NoSuchAlgorithmException, IOException, NoSuchProviderException, KeyStoreException, UnrecoverableKeyException {
        String pathSrc = "rsa.lzc.jks";
        String pathDst = "rsa.lzc.pfx";
        String passwd = "12345678";

        JksToPfx.ToPFX(pathSrc, pathDst, passwd.toCharArray());
    }
}
